var express = require('express');
var router = express.Router();
const { Chapter,Course } = require('../../models');
const { Op } = require('sequelize');

const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {
        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;
        
        if (!query.courseId) {
            throw new Error('获取章节列表失败，课程ID不能为空')
        }

        const condition = {
            ...getCondition(),
            order: [['rank', 'ASC'],['id', 'ASC']],
            offset: offset,
            limit: pageSize
        }
        condition.where = {
            courseId: {
                [Op.eq]: query.courseId
            }
        }
        if (query.title) {
            condition.where.title = {
                [Op.like]: `%${query.title}%`
            }
        }
        const { count, rows } = await Chapter.findAndCountAll(condition);
        success(
            res,
            '查询章节列表成功',
            {
                chapter: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询章节详情
router.get('/:id', async function (req, res, next) {
    try {
        const chapter = await getChapter(req);
        success(
            res,
            '查询章节成功',
            {chapter}
        )

    } catch (error) {
        failure(res, error)
    }
});


// 新建章节
router.post('', async function (req, res, next) {
    try {
        const body = filterBody(req.body)
        const chapter = await Chapter.create(body)
        success(
            res,
            '创建章节成功',
            {chapter}
        )
    } catch (error) {
        failure(res, error)
    }
});

// 删除章节
router.delete('/:id', async function (req, res, next) {
    try {
        const chapter = await getChapter(req);
        
        // 查询当前列是否有章节
        count = await Course.count({ where: { chapterId: req.params.id } });
        if (count > 0) {
            throw new Error('当前章节有章节，无法删除')
        }

        await chapter.destroy()
        success(
            res,
            '删除章节成功'
        )
    } catch (error) {
        failure(res, error)
    }
});

// 更新章节
router.put('/:id', async function (req, res, next) {
    try {
        const chapter = await getChapter(req);
        const body = filterBody(req.body)
        await chapter.update(body)
        success(
            res,
            '更新章节成功', {
                chapter
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 过滤body 和 name
const filterBody = (body)=>{
    return {
        courseId: body.courseId,
        title: body.title,
        content: body.content,
        video: body.video,
        rank: body.rank,
    }
}


/**
 * 查询当前章节
 * @param {*} req 
 */
async function getChapter(req) {
    const { id } = req.params;
    const condition = getCondition();
    const chapter = await Chapter.findByPk(id,condition);
    if (!chapter) {
        throw new NotFoundError(`ID: ${id}的章节未找到`)
    }
    return chapter;
}

/** 公共方法：关联课数据 */
const getCondition = () => {
    return {
        attributes: { exclude: ['CourseId'] },
        include: [
            { model: Course, as: 'course', attributes: ['id', 'name'] },
        ]
    }
}

module.exports = router;
